package com.cetcs.kmga.dataManager.service.impl.sysManager;

import com.cetc.cloud.kmga.util.EmailManager;
import com.cetc.cloud.kmga.util.SigarUtils;
import com.cetcs.kmga.common.Data;
import com.cetcs.kmga.common.Page;
import com.cetcs.kmga.dataManager.dao.mybatis.CleanRecordLogMapper;
import com.cetcs.kmga.dataManager.dao.mybatis.SysManagerMapper;
import com.cetcs.kmga.dataManager.entity.device.DeviceInfo;
import com.cetcs.kmga.dataManager.entity.sysManager.LocalServerInfo;
import com.cetcs.kmga.dataManager.entity.sysManager.SysEmailSerConf;
import com.cetcs.kmga.dataManager.entity.sysManager.vi.SysEmailSerConfVi;
import com.cetcs.kmga.dataManager.entity.sysManager.vo.ServerStatusVo;
import com.cetcs.kmga.dataManager.entity.sysManager.vo.SpaceAccountedVo;
import com.cetcs.kmga.dataManager.global.DataManagerConstants;
import com.cetcs.kmga.dataManager.schedule.InitCdTypeListener;
import com.cetcs.kmga.dataManager.service.sysManager.SysManagerService;
import com.cetcs.kmga.dataManager.util.EhcacheUtil;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.google.common.collect.Lists;
import net.sf.ehcache.Element;
import org.hyperic.sigar.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import java.util.List;


/**
 * Created by yyangs on 2017/2/14.
 */
@Service
public class SysManagerServiceImpl implements SysManagerService {

    @Autowired
    private SysManagerMapper sysManagerMapper;
    @Autowired
    private CleanRecordLogMapper cleanRecordLogMapper;


    /**
     * 获取本地服务器的信息
     *
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public LocalServerInfo getLocalServiceInfo(Data dataMap) throws Exception {
        return sysManagerMapper.getLocalServiceInfo(dataMap);
    }

    /**
     * 更新本地服务器的信息
     *
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public Integer updateLocalServiceInfo(Data dataMap) throws Exception {
        return sysManagerMapper.updateLocalServiceInfo(dataMap);
    }

    /**
     * 获取本地服务器的状态信息
     *
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public ServerStatusVo getServiceStatus(Data dataMap) throws Exception {
        ServerStatusVo serverStatusVo = new ServerStatusVo();
        Sigar sigar = SigarUtils.sigar;
        if(sigar!=null) {
            CpuPerc cpu = sigar.getCpuPercList()[0];
            serverStatusVo.setCpuValue(Double.valueOf(CpuPerc.format(cpu.getCombined()).replace("%","")));
            Mem mem = sigar.getMem();
            serverStatusVo.setDataValue(Double.valueOf((float) mem.getUsed() / (float) mem.getTotal()*100));
            FileSystem fslist[] = sigar.getFileSystemList();
            FileSystemUsage usage = sigar.getFileSystemUsage(fslist[0].getDirName());
            serverStatusVo.setIoValue(Double.valueOf((float) usage.getUsed() / usage.getTotal()*100));
        }
        return serverStatusVo;
    }

    /**
     * 获取获取本机的空间占比数据
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public List<SpaceAccountedVo> getLocalSpaceAccounted(Data dataMap) throws Exception {
        return cleanRecordLogMapper.getLocalSpaceAccounted(dataMap);
    }

    /**
     * 获取清理日志  分页
     *
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public Page getCleanRecordsByPage(Data dataMap) throws Exception {
        List<DeviceInfo> resultList = Lists.newArrayList();
        try {
            resultList = cleanRecordLogMapper.getCleanRecordsByPageAndCondition(dataMap, new PageBounds(dataMap.getInt("page"), dataMap.getInt("pageSize")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        PageList<DeviceInfo> pageList = (PageList<DeviceInfo>) resultList;
        return new Page(pageList);
    }

    /**
     * 添加清理日志
     * @param dataMap
     * @return
     * @throws Exception
     */
    @Override
    public Integer addCleanRecords(Data dataMap) throws Exception {
        return cleanRecordLogMapper.addCleanRecords(dataMap);
    }


    /**
     * =========xutao= start====================
     */
    /**
     * 更新或创建服务配置
     *
     * @param record
     * @return
     */
    @Override
    public int createOrModifySysEmailConfig(SysEmailSerConfVi record) {
        int ret = 0;
        SysEmailSerConf emailSerConf = sysManagerMapper.findSysEmailSerConf();
        if (emailSerConf != null) {
            record.setId(emailSerConf.getId());
            ret = sysManagerMapper.modifySysEmailSerConfig(record);
        } else {
            ret = sysManagerMapper.createSysEmailSerConfig(record);
        }
        reloadSysEmailConf2Cache();
        return ret;
    }

    /**
     * 查询邮箱服务的配置
     *
     * @param
     * @return
     */
    @Override
    public SysEmailSerConf findSysEmailConfig() {
        SysEmailSerConf serConf = null;
        EhcacheUtil ehcacheUtil = new EhcacheUtil(DataManagerConstants.SYS_EMAIL_EHCACHE_NAME);
        if (ehcacheUtil.get(DataManagerConstants.SYS_EMAIL_EHCACHE_ELEMENT_NAME) != null) {
            Element serConfElement = ehcacheUtil.get(DataManagerConstants.SYS_EMAIL_EHCACHE_ELEMENT_NAME);
            serConf = (SysEmailSerConf) serConfElement.getObjectValue();
        } else {
            serConf = sysManagerMapper.findSysEmailSerConf();
        }
        return serConf;
    }

    @Override
    public void reloadSysEmailConf2Cache() {
        SysEmailSerConf serConf = sysManagerMapper.findSysEmailSerConf();
        EhcacheUtil ehcacheUtil = new EhcacheUtil(DataManagerConstants.SYS_EMAIL_EHCACHE_NAME);
        if (ehcacheUtil.get(DataManagerConstants.SYS_EMAIL_EHCACHE_ELEMENT_NAME) != null) {
            ehcacheUtil.remove(DataManagerConstants.SYS_EMAIL_EHCACHE_ELEMENT_NAME);
        }
        Element newEle = new Element(DataManagerConstants.SYS_EMAIL_EHCACHE_ELEMENT_NAME, serConf);
        ehcacheUtil.put(newEle);
    }

    @Override
    public void verifySysEmailSer(SysEmailSerConfVi record) throws UnsupportedEncodingException, MessagingException {

        EmailManager emailManager = new EmailManager(record.getHost(),
                record.getPort(), record.getSenderNick(), record.getFrom(), record.getUserName(), record.getPassword());
        String subject = "请查收邮件";
        String content = "请确认是否收到邮件！请查收";
         emailManager.sendMail(record.getTestEmail(), subject, content);
    }

    /**
     * =========xutao= end====================
     */
}
